package com.my.socket.nio.v21;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.SocketChannel;
import java.util.Iterator;
import java.util.Set;

/**
 * Created by ZhongGang
 * at 2018/7/4 17:03
 */
public class ReadWriteTask implements Runnable {
    private static final Logger LOGGER = LoggerFactory.getLogger(ReadWriteTask.class);

    private Selector readWriteSelector;
    private ByteBuffer byteBuffer = ByteBuffer.allocate(1024);

    public ReadWriteTask(Selector readWriteSelector) {
        this.readWriteSelector = readWriteSelector;
    }

    @Override
    public void run() {
        while (true) {
            try {
                int select = this.readWriteSelector.selectNow();
                if (select == 0) {
                    continue;
                }
                LOGGER.info("{} event(s) incoming......", select);

                Set<SelectionKey> selectionKeys = this.readWriteSelector.selectedKeys();
                Iterator<SelectionKey> iterator = selectionKeys.iterator();
                while (iterator.hasNext()) {
                    SelectionKey selectionKey = iterator.next();
                    iterator.remove();

                    if (selectionKey.isReadable()) {
                        /**
                         * 关闭客户端，服务端会发生一个read事件，并且在read的时候抛出异常，来表示关闭
                         * 这个事件会不断发生，就算从已准备好的集合移除也没有，必须将该channel关闭或者调用哪个该key的cancel方法
                         *
                         * 因为SelectionKey代表的是Selector和Channel之间的联系，所以在Channel关闭了之后，对于Selector来说，这个Channel永远都会发出关闭这个事件，表明自己关闭了，直到从该Selector移除去
                         */
                        selectionKey.cancel();

                        SocketChannel socketChannel = (SocketChannel) selectionKey.channel();
                        StringBuilder messageBuilder = new StringBuilder();
                        int read = socketChannel.read(byteBuffer);
                        while (read > 0) {
                            byteBuffer.flip();
                            messageBuilder.append(new String(byteBuffer.array(), 0, read));
                            byteBuffer.clear();
                            read = socketChannel.read(byteBuffer);
                        }
                        String request = messageBuilder.toString();
                        LOGGER.info("read: {}", request);

                        String response = request.toUpperCase();
                        socketChannel.write(ByteBuffer.wrap(response.getBytes()));
                        LOGGER.info("write: {}", response);

                        socketChannel.close();
                    } else {
                        LOGGER.info("unhandled selection key: {}", selectionKey);
                    }
                }
            } catch (Exception e) {
                LOGGER.error("exception caught, the error is {}", e.getMessage());
            }
        }
    }
}
